package com.yanhao.viewmode

import androidx.lifecycle.*
import com.yanhao.bean.WxArticle
import com.yanhao.etx.error
import com.yanhao.repository.NavigationFgRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException

class NavigationFgViewModel(private val repository: NavigationFgRepository) : BaseViewModel() {

    private var _wxArticles = MutableLiveData<MutableList<WxArticle>>()
    val wxArticles: LiveData<MutableList<WxArticle>> = _wxArticles

    fun getWxArticlesData() {
        viewModelScope.launch {
            flow {
                val result = repository.getWxArticles()
                emit(result)
            }.flowOn(Dispatchers.IO)
                .onStart {

                }.catch { e: Throwable ->
                    errorCatch(e)
                }.flowOn(Dispatchers.Main).onCompletion {

                }.collect {
                    it?.let {
                        if (it.errorCode == 0) {
                            _wxArticles.value = it.data!!
                        }
                    }
                }
        }
    }
}

class NavigationFgViewModelFactory() : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(NavigationFgViewModel::class.java)) {
            return NavigationFgViewModel(repository = NavigationFgRepository()) as T
        }
        throw IllegalArgumentException("不能找到 NavigationFgRepository ")
    }

}